package com.efrei.uchat.client.gui.conf;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.efrei.uchat.utils.Const;

public class ServerConfig {

	private static Logger logger = Logger.getLogger(ServerConfig.class);
	private Properties config;
	
	private String filePath;
	private String host;
	private int port;
	private String pseudo;
	
	/**
	 * read conf file or return default values if conf not exists
	 * @param filePath
	 */
	public ServerConfig(String filePath) {
		this.filePath = filePath;
		
		if(pseudo==null) {
			pseudo = "";
		}
		logger.info("read conf file "+filePath);
		
		config = new Properties();
		InputStream input = null;
		try {
			input = new FileInputStream(filePath);
			config.load(input);
			host = config.getProperty("host");
			port = Integer.valueOf(config.getProperty("port"));
			pseudo = config.getProperty("pseudo");
			logger.info(String.format("Success read for %s %s:%s", pseudo, host, port));
		} catch(Exception e) {
			logger.info("Error with config load, use default values");
			setDefaultValues();
		} finally {
			try {
				if(input!=null)
					input.close();
			} catch(Exception e) {
				//e.printStackTrace();
			}
		}
	}
	
	private void setDefaultValues() {
		host = Const.DEFAULT_HOST;
		port = Const.DEFAULT_PORT;
		// default: system's username
		pseudo = System.getProperty("user.name");
	}
	
	/**
	 * save current values in conf file
	 * @throws IOException
	 */
	public void save() throws Exception {
		FileOutputStream output = new FileOutputStream(filePath);
		try {
			config.put("host", host);
			config.put("port", String.valueOf(port));
			config.put("pseudo", pseudo);
			config.store(output, "UChat client configuration");
		} finally {
			output.close();
		}
	}
	
	@Override
	public String toString() {
		return "ServerConfig [host=" + host + ", port=" + port + ", pseudo="
				+ pseudo + "]";
	}

	public String getHost() {
		return host;
	}
	
	public int getPort() {
		return port;
	}
	
	public String getPseudo() {
		return pseudo;
	}
	
	public void setHost(String host) {
		this.host = host;
	}
	
	public void setPort(int port) {
		this.port = port;
	}
	
	public void setPseudo(String pseudo) {
		this.pseudo = pseudo;
	}
}
